const db = wx.cloud.database()
const _ = db.command
var util = require('../../utils/util.js')
Page({
  data: {
    TabCur: 0,
    navTab: ['维修申请单', '历史维修单'],
    orderlist: {},
    btnText: '',
    page: 0
  },

  LoadUnCompletedForm(isReachBottom) {
    var page = this.data.page
    wx.showLoading({
      title: '数据加载中...',
    })
    db.collection('order').where({
      step: _.lte(2),
    }).skip(page).orderBy('step', 'asc')
      .orderBy('submitdate', 'desc')
      .get().then(res => {
        for (var index in res.data) {
          res.data[index].time = util.formatTime(res.data[index].submitdate)
          res.data[index].completetime = util.formatTime(res.data[index].completedate)
          if (res.data[index].step == 1)
            res.data[index].btnText = '等待派单'
          else
            res.data[index].btnText = '已派单'
        }
        var orderlist = this.data.orderlist
        if (isReachBottom == 1)
          orderlist = orderlist.concat(res.data)
        else
          orderlist = res.data
        this.setData({
          orderlist: orderlist
        })
        wx.hideLoading()
      })
  },

  LoadCompletedForm(isReachBottom) {
    var page = this.data.page
    wx.showLoading({
      title: '数据加载中...',
    })
    db.collection('order').where({
      step: _.gte(3),
    }).skip(page).orderBy('submitdate', 'desc')
      .get().then(res => {
        for (var index in res.data) {
          res.data[index].time = util.formatTime(res.data[index].submitdate)
          res.data[index].completetime = util.formatTime(res.data[index].completedate)
          if (res.data[index].step == 3)
            res.data[index].btnText = '待评价'
          else
            res.data[index].btnText = '已完成'
        }
        var orderlist = this.data.orderlist
        if (isReachBottom == 1)
          orderlist = orderlist.concat(res.data)
        else
          orderlist = res.data
        this.setData({
          orderlist: orderlist
        })
        wx.hideLoading()
      })
  },

  onLoad: function (options) {
    if (this.data.TabCur == 0) {
      this.LoadUnCompletedForm(0)
    } else if (this.data.TabCur == 1) {
      this.LoadCompletedForm(0)
    }
  },
  
  onShow: function () {
    this.onLoad()
  },

  tabSelect(e) {
    this.setData({
      TabCur: e.currentTarget.dataset.id, page: 0
    })
    if (this.data.TabCur == 0) {
      this.LoadUnCompletedForm(0)
    } else if (this.data.TabCur == 1) {
      this.LoadCompletedForm(0)
    }
  },

  onReachBottom: function () {
    console.log("onReachBottom")
    var page = this.data.page + 20
    this.setData({
      page: page
    })
    if (this.data.TabCur == 0) {
      this.LoadUnCompletedForm(1)
    } else if (this.data.TabCur == 1) {
      this.LoadCompletedForm(1)
    }
  },

  manageorder: function (event) {
    wx.navigateTo({
      url: '../formdetail/formdetail?authority=1&id=' + event.currentTarget.dataset.id
    })
  }
})